package com.gxa.wmcrm.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gxa.wmcrm.entity.Employee;
import com.gxa.wmcrm.entity.Page;
import com.gxa.wmcrm.service.EmployeeService;
import com.gxa.wmcrm.service.Impl.EmployeeServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@WebServlet(name = "QueryEmployeeByPageServlet", urlPatterns = "/QueryEmployeeByPageServlet")
public class QueryEmployeeByPageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/json; charset=utf-8");
        InputStream inputStream = request.getInputStream();
        InputStreamReader reader = new InputStreamReader(inputStream, "UTF-8");
        // 字符缓冲区
        char[] buff = new char[1024];
        int length = 0;
        String jsonstr = null;
        while ((length = reader.read(buff)) != -1) {
            // 通过String的构造方法将 字符缓冲区 转化为一个String
            jsonstr = new String(buff, 0, length);
            System.out.println(jsonstr);
            //jsonstr = {login: login, pwd: pwd, code: code, AdminCode: AdminCode};
        }
        // 通过 FastJSON方法 将JSON结构的字符串转为 map
        Map<String, Object> parameters = JSONObject.parseObject(jsonstr);
        System.out.println("parameters ：" + parameters);
        //为Page对象赋值
        Page page = new Page();
        int currentPage = (Integer) parameters.get("currentPage");
        int perSize = (Integer) parameters.get("perSize");
        page.setCurrentPage(currentPage);
        page.setPerSize(perSize);
        //调用queryEmployeeByPage(含参)方法获取Employee集合
        List<Employee> list = new ArrayList<Employee>();
        EmployeeService employeeService = new EmployeeServiceImpl();
        list = employeeService.queryEmployeeByPage(page);
        //返回集合信息
        String str = JSON.toJSONString(list);
        System.out.println("str =" + str);
        PrintWriter out = response.getWriter();
        out.print(str);
    }
}